<template>
  <div class="article-container">
    <!-- 搜索区域 -->
    <el-card class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true">

        <el-form-item label="标题" prop="title">
          <el-input v-model="queryParams.title" placeholder="请输入标题" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="queryParams.author" placeholder="请输入作者" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="状态" prop="state" >
          <el-select v-model="queryParams.state" placeholder="请选择状态" clearable style="width: 200px">
            <el-option label="上架" value="0" />
            <el-option label="下架" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文章管理</span>
          <el-button type="primary" @click="handleAdd">新增文章</el-button>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="标题" />
        <!-- 图片上传 -->
        <el-table-column prop="picUrl" label="宣传图" >
          <template #default="{ row }">
            <el-image style="width: 50px; " :src="row.picUrl" fit="contain" />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" show-overflow-tooltip >
          <template #default="{ row }">
            <el-button @click="openPreview(row.content)"> 预览</el-button>
          </template>

        </el-table-column>
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="publishTime" label="发布时间" width="180" />
        <el-table-column prop="state" label="状态" width="100">
          <template #default="scope">
            {{ scope.row.state === 0 ? '上架' : '下架' }}
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" />
        <el-table-column prop="articleType" label="类型" width="100">
          <template #default="scope">
            {{ scope.row.articleType === 0 ? '图文' : '视频' }}
          </template>
        </el-table-column>
        <el-table-column prop="readCount" label="阅读数" width="100" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="标题" required>
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="宣传图片">
          <div class="upload-box">
            <el-upload
                    class="upload-demo"
                    action=""
                    :http-request="uploadImage"
                    :show-file-list="true"
                    :file-list="imageList"
                    list-type="picture-card"
                    :on-remove="handleImageRemove"
                    :limit="1"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </div>
          <div class="upload-tip">支持jpg、png格式，单张不超过10M，只能上传一张</div>
        </el-form-item>
        <el-form-item label="类型" required>
          <el-select v-model="form.articleType" @change="handleTypeChange">
            <el-option label="图文" :value="0" />
            <el-option label="视频" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" required>
          <TEditor v-model="htmlContent"> </TEditor>
        </el-form-item>

        <!-- 视频上传 -->
        <el-form-item label="视频" v-if="form.articleType === 1">
          <div class="upload-box">
            <el-upload
              class="upload-video"
              action=""
              :http-request="uploadVideo"
              :show-file-list="true"
              :file-list="videoList"
              :on-remove="handleVideoRemove"
              accept=".mp4"
            >
              <el-button type="primary">上传视频</el-button>
            </el-upload>
          </div>
          <div class="upload-tip">支持mp4格式，单个视频不超过100M</div>
        </el-form-item>

        <el-form-item label="作者">
          <el-input v-model="form.author" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.state">
            <el-option label="上架" :value="0" />
            <el-option label="下架" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="previewVisible" title="H5内容预览" width="90%">
      <div
              v-html="h5Content"
              style="height:70vh; border:none;overflow-y: auto;"
      ></div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import {ref, onMounted, reactive} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getArticleList, addArticle, updateArticle, deleteArticle } from '@/api/article'
import TEditor from "@/components/TEditor.vue"

const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const imageList = ref([])
const videoList = ref([])
  const previewVisible = ref(false)

  const h5Content = ref(''); // 从接口或本地获取的
  const dynamicId = ref('')
const form = ref({
  articleId: undefined,
  title: '',
  content: '',
  author: '',
  state: 0,
  sort: 0,
  articleType: 0
})

  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    title: '',
    author: '',
    state: ''
  })

const htmlContent = ref('');
  // 查询
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }

  // 重置
  const resetQuery = () => {
    queryParams.title = ''
    queryParams.author = ''
    queryParams.state = undefined
    handleQuery()
  }
  const openPreview = (content: string) => {
    h5Content.value  = content;
    previewVisible.value  = true
  }
const getContent = () => {
  console.log('当前内容:', htmlContent.value);
  form.value.content = htmlContent.value
};

// 类型切换处理
const handleTypeChange = (val: number) => {
  // 清空已上传的文件
  imageList.value = []
  videoList.value = []
}

// 上传图片
const uploadImage = async (params: any) => {
  try {
    const formData = new FormData()
    formData.append('file', params.file)

    const res = await fetch('/api/common/upload', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('Admin-Token')
      },
      body: formData
    })

    const result = await res.json()
    if (result.code === 200) {
      imageList.value.push({
        name: params.file.name,
        url: result.url
      })
      form.value.picUrl = result.url
    } else {
      ElMessage.error(result.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 上传视频
const uploadVideo = async (params: any) => {
  try {
    const formData = new FormData()
    formData.append('file', params.file)
    console.log('localStorage',localStorage)
    const res = await fetch('/api/common/upload', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('Admin-Token')
      },
      body: formData
    })

    const result = await res.json()
    if (result.code === 200) {
      videoList.value.push({
        name: params.file.name,
        url: result.url
      })
      // 更新content字段，将视频URL添加到内容中
      form.value.content = result.url
    } else {
      ElMessage.error(result.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 删除图片
const handleImageRemove = (file: any) => {
  const index = imageList.value.findIndex(item => item.url === file.url)
  if (index !== -1) {
    imageList.value.splice(index, 1)
    // 从content中移除对应的图片URL
    form.value.content = form.value.content.replace(`\n[图片]${file.url}`, '')
  }
}

// 删除视频
const handleVideoRemove = (file: any) => {
  const index = videoList.value.findIndex(item => item.url === file.url)
  if (index !== -1) {
    videoList.value.splice(index, 1)
    // 清空content中的视频URL
    form.value.content = ''
  }
}

// 获取文章列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getArticleList(queryParams)
    console.log(res)
    tableData.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 新增文章
const handleAdd = () => {
  form.value = {
    articleId: undefined,
    title: '',
    content: '',
    author: '',
    state: 0,
    sort: 0,
    articleType: 0
  }
  htmlContent.value = ''
  imageList.value = []
  videoList.value = []
  dialogTitle.value = '新增文章'
  dialogVisible.value = true
}

// 编辑文章
const handleEdit = (row: any) => {
  form.value = { ...row }

  // 根据content解析已上传的文件
  if (row.articleType === 0) {
    imageList.value.push({
      name: '宣传图',
      url: row.picUrl
    })
    // // 解析图片URL
    // const urls = row.content.match(/\[图片\](.*?)(?=\n|$)/g) || []
    // imageList.value = urls.map((item: string) => ({
    //   name: '已上传图片',
    //   url: item.replace('[图片]', '')
    // }))
  } else {
    // 视频类型
    if (row.content) {
      videoList.value = [{
        name: '已上传视频',
        url: row.content
      }]
    }
  }
  dialogTitle.value = '编辑文章'
  dialogVisible.value = true

  htmlContent.value =  form.value.content
  console.log('htmlContent',htmlContent.value)
}

// 删除文章
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该文章吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteArticle(row.articleId)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  getContent()
  if (!form.value.title) {
    ElMessage.warning('请输入标题')
    return
  }
  if (!form.value.content) {
    ElMessage.warning('请输入内容')
    return
  }
  // if (form.value.articleType === 0 && imageList.value.length === 0) {
  //   ElMessage.warning('请上传图片')
  //   return
  // }
  if (form.value.articleType === 1 && videoList.value.length === 0) {
    ElMessage.warning('请上传视频')
    return
  }

  try {
    if (form.value.articleId) {
      await updateArticle(form.value)
      ElMessage.success('更新成功')
    } else {
      await addArticle(form.value)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error)
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.article-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.upload-box {
  margin-bottom: 10px;
}
.upload-tip {
  font-size: 12px;
  color: #999;
}
.upload-video {
  :deep(.el-upload-list__item) {
    width: 100%;
  }
}
</style>
